﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyVoteMVC.ExcelObject;
using MyVoteMVC.BackstageManagement.Views;
using MyVoteMVC.Data.Repositories;
using MyVoteMVC.Domain;
using MyVoteMVC.Common;
using MyVoteMVC.Data;
using MyVoteMVC.BackstageManagement.Extensions;
using System.IO;
using System.Drawing;
 

namespace MyVoteMVC.BackstageManagement.Controllers
{

    public class ProjectsImportorController : IProjectsImportorController
    {
        #region model

        IAdminRepository<VT_Projects> projectsRepositrty;
        IUnitOfWork unitOfWork;
        ExcelHelper helper;

        IProjectsImportorView view;

        #endregion

        public ProjectsImportorController(IProjectsImportorView view)
        {
            this.view = view;
            unitOfWork = Factory.GetInstance<IUnitOfWork>();
            projectsRepositrty = unitOfWork.GetAdminRepository<VT_Projects>();
        }

        public IView<Project> Form
        {
            get
            {
                return this.view;
            }
        }

        public void Load()
        {

        }

        public void LoadExcelFile(string fileName)
        {
            helper = new ExcelHelper(fileName);
            view.LoadExcelFileComplete(helper.GetWorksheetNames());
        }

        public void ExcelQuery(string mapingName, 
            string mappingType, 
            string mappingYear, 
            string mappingAddress,
            string mappingAwards,
            string mappingDescription,
            string mappingImgFolder,
            List<string> sheetToConvert)
        {
            helper.AddMapping<Project>(o => o.Project_Name, mapingName);
            helper.AddMapping<Project>(o => o.Project_Address, mappingAddress);
            helper.AddMapping<Project>(o => o.Project_Type, mappingType);
            helper.AddMapping<Project>(o => o.Project_Year, mappingYear);
            helper.AddMapping<Project>(o => o.Project_Awards, mappingAwards);
            helper.AddMapping<Project>(o => o.Project_Description, mappingDescription);
            IList<Project> projects = new List<Project>();
            
            foreach(string sheet in sheetToConvert)
            {
                var temp = helper.Query<Project>(sheet);
                if (temp != null)
                {
                    if (projects != null)
                        projects = projects.Union(temp).ToList();
                    else
                        projects = temp;
                }
            }
            
            foreach (Project project in projects)
            {
                string finalImgPath = "";
                string imgPngPath = mappingImgFolder + "\\" +project.Project_Name + ".png";
                if (File.Exists(imgPngPath))
                {
                    finalImgPath = imgPngPath;
                }
                else
                {
                    string imgJpgPath = mappingImgFolder + "\\" + project.Project_Name + ".jpg";
                    if (File.Exists(imgJpgPath))
                    {
                        finalImgPath = imgJpgPath;
                    }
                    else
                    {
                        string imgGifPath = mappingImgFolder + "\\" + project.Project_Name + ".gif";
                        if (File.Exists(imgGifPath))
                        {
                            finalImgPath = imgGifPath;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(finalImgPath))
                    project.Project_Image = ReadFile(finalImgPath);
            }
            
            view.ExcelQueryComplete(projects);
        }

        public void DBSubmit(IList<Project> projects)
        {
            try
            {
                var vtprojects = projects.ToNewEntityList(new ProjectModelConverter());
                unitOfWork.BeginTransaction();
                foreach (VT_Projects project in vtprojects)
                {
                    projectsRepositrty.Add(project);
                }
                unitOfWork.CommitTransaction();
                view.DBSubmitComplete("转换成功");
            }
            catch(Exception ex)
            {
                view.DBSubmitComplete(ex.Message);
            }
        }

        private byte[] ReadFile(string fileName)
        {
            bool isBroken = false;
            try
            {
                Bitmap bmp = new Bitmap(fileName);
                if (bmp == null)
                {
                    //图片损坏
                    isBroken = true;
                }
            }
            catch //(Exception ex)
            {
                //图片损坏
                isBroken = true;
            }

            if (isBroken)
                return null;
            FileStream pFileStream = null;
            byte[] pReadByte = new byte[0];

            try
            {
                pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(pFileStream);
                r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开
                pReadByte = r.ReadBytes((int)r.BaseStream.Length);
                return pReadByte;
            }
            catch
            {
                return pReadByte;
            }
            finally
            {
                if (pFileStream != null)
                    pFileStream.Close();
            }
        }
    }
}
